<template>
  <div class="login">
    <a-form layout="vertical" ref="formRef" :model="formState" :rules="rules">
      <a-form-item label="手机号" name="phone">
        <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
      </a-form-item>
      <a-form-item label="密码" name="password">
        <a-input v-model:value="formState.password" type="password" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" block @click="submit" :loading="loading">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang='ts'>
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { login } from '@/services/user'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { message } from 'ant-design-vue'

// 验证
const validateForm = () => {
  const formRef = ref()
  const rules = {
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { len: 11, message: '手机号长度错误', trigger: 'blur' }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }
  const validata = () => {
    return formRef.value.validate()
  }
  return {
    formRef,
    rules,
    validata
  }
}

export default defineComponent({
  setup () {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const { formRef, rules, validata } = validateForm()

    // 登录
    const submitLogin = () => {
      const formState = reactive({
        phone: '',
        password: ''
      })

      onMounted(() => {
        formState.phone = '18201288771'
        formState.password = '111111'
      })

      const loading = ref(false)

      const submit = async (): Promise<void> => {
        loading.value = true
        try {
          await validata()
          const { data } = await login(formState)

          if (data.state !== 1) {
            message.error(data.message)
          } else {
            store.commit('setUser', data.content)
            router.push(route.query.redirect as string || '/')
          }
        } catch (error) { }
        loading.value = false
      }
      return {
        loading,
        formState,
        submit
      }
    }
    return {
      formRef,
      rules,
      validata,
      ...submitLogin()
    }
  }
})
</script>
<style lang="scss" scoped>
.login {
  width: 400px;
  margin: 300px auto;
  padding: 20px;
  border-radius: 5px;
  background-color: #fff;
}
</style>
